package chapter6_2_condition;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.AbstractQueuedSynchronizer;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;

/**
 * @author Summerday
 */
public class Mutex implements Lock, java.io.Serializable {

    // AQS的实现
    private static final Sync sync = new Sync();


    public boolean isLocked() {
        return sync.isHeldExclusively();
    }

    public void lock() {
        sync.acquire(1);
    }

    @Override
    public void lockInterruptibly() throws InterruptedException {
        sync.acquireInterruptibly(1);
    }

    public boolean tryLock() {
        return sync.tryAcquire(1);
    }

    @Override
    public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
        return sync.tryAcquireNanos(1, unit.toNanos(time));
    }

    @Override
    public void unlock() {
        sync.release(1);
    }

    @Override
    public Condition newCondition() {
        return sync.condition();
    }


    static class Sync extends AbstractQueuedSynchronizer {

        // 尝试获取资源,获取成功设置state为1,返回true,否则返回false
        @Override
        protected boolean tryAcquire(int acquires) {
            final Thread current = Thread.currentThread();
            assert acquires == 1; // 只能为1
            if (compareAndSetState(0, 1)) { // cas 设置state 0 -> 1
                setExclusiveOwnerThread(current); // 设置当前线程得到了这个资源
                return true;
            }
            return false;
        }

        // 尝试释放资源,释放成功设置state为0,返回true,否则返回false
        @Override
        protected boolean tryRelease(int releases) {
            assert releases == 1; // 只能为1
            if (getState() == 0) { // 没有获取资源就来释放锁,肯定是不行的
                throw new IllegalMonitorStateException();
            }
            setExclusiveOwnerThread(null); // 重置
            setState(0); // 重置为0
            return true;
        }

        // 判断是否为锁定状态
        @Override
        protected boolean isHeldExclusively() {
            return getState() == 1;
        }

        public Condition condition() {
            return new ConditionObject();
        }

        // 自定义序列化
        private void readObject(ObjectInputStream s) throws IOException, ClassNotFoundException {
            s.defaultReadObject();
            setState(0); //重置为解锁的状态
        }
    }

}
